package BLC

import (
	"log"

	"github.com/boltdb/bolt"
)

type BlockChainIterator struct {
	DB          *bolt.DB
	BlockChain  *BlockChain
	CurrentHash []byte
}

//迭代器
func (self *BlockChain) Iterator() *BlockChainIterator {
	return &BlockChainIterator{
		DB:          self.DB,
		BlockChain:  self,
		CurrentHash: self.Tip,
	}
}

//下一个
func (self *BlockChainIterator) Next() *Block {

	var block *Block
	_ = self.DB.View(func(tx *bolt.Tx) error {
		bucket := tx.Bucket([]byte(BlockDB))
		if bucket == nil {
			log.Panicln("没有找到这个桶")
			return nil
		}
		blockHash := bucket.Get(self.CurrentHash)
		block = DeserializeBlocker(blockHash)

		self.CurrentHash = block.PrevBlockHash
		return nil
	})

	return block
}
